#!/usr/bin/env python
# -*- coding: UTF-8 -*-

try:
	import math
	import pygame
	import sys
	from math import ceil
	from pygame.event import Event
	from pygame.locals import *
	from utils import *
except ImportError, err:
	print "Could not load %s module." % (err)
	sys.exit(2)

'''
Animatable "Interface"
A sprite that inherits this class must do the following:

1. Call Animatable.__init__(self) on its own __init__()
2. Call self.set_anim_params(distance_in_px, duration_in_frames) as
   soon as those params are known
3. Have a move() that sets self.moving to an int direction or zero
4. Have an update() that, if self.moving is true, calls self.slide()
   and then uses the new x and y values

Current directions are set to the arrow keys. Should probably become
their own constants (perhaps stored in utils.py).

Could also create Moveable.py. Or rename Animatable to Movable and
add the move() and r_move() methods right here (direction boundary
variables would have to be set).

Yikes. Pretty much every object uses x & y differently.
Major rework pending.
'''

SLIDE_DURATION = 6

class Animatable(object):
	def __init__(self):
		object.__init__(self)
		self.x = 0
		self.y = 0
		self.moving = 0
		self.end_event = Event(USEREVENT, {'name' : 'ANIM_END'})

	def set_anim_params(self, distance, duration = SLIDE_DURATION):
		self.px_remaining = distance
		self.frames_left = duration
		self.orig_dist_dur = (distance, duration)

	def set_end_event_name(self, name):
		self.end_event = Event(USEREVENT, {'name' : name})

	def slide(self):
		if self.frames_left == 1:
			step = self.px_remaining
		else:
			step = int(ceil(self.px_remaining / self.frames_left))

		if self.moving == K_UP:
			self.y -= step
		elif self.moving == K_RIGHT:
			self.x += step
		elif self.moving == K_DOWN:
			self.y += step
		elif self.moving == K_LEFT:
			self.x -= step
		self.frames_left -= 1
		self.px_remaining -= step
		if not self.px_remaining:
			self.moving = 0
			(self.px_remaining, self.frames_left) = self.orig_dist_dur
			pygame.event.post(self.end_event)
